package com.itheima.thread.threadPool.semaphore;

import java.util.Stack;
import java.util.concurrent.Semaphore;

/**
 * @Author: Ethan Yankang
 * @Program: Interview
 * @Date: 2024-08-16 09:16
 **/
public class semaphoreExample {

    public static void main(String[] args) {
        // 1. 创建 semaphore 对象
        Semaphore semaphore = new Semaphore(3);
//        保护并发访问某一资源或执行某一段代码的线程数量，这里就是try块里面的内容。
        // 2. 10个线程同时运行
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    // 3. 获取许可
                    System.out.println(Thread.currentThread().getName()+"获得了许可");
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    System.out.println(Thread.currentThread().getName()+"running");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"end");
                } finally {
                    // 4. 释放许可
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName()+"释放了许可");

                }
            }).start();
        }
    }
}
